package com.zzyl.controller;

import cn.hutool.http.server.HttpServerRequest;
import com.zzyl.base.ResponseResult;
import com.zzyl.entity.SysUser;
import com.zzyl.mapper.SysUserMapper;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginUserVo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * BaseController
 * web层通用数据处理
 * @author itheima
 **/
@Api(tags = "基础控制器，提供一些公共方法")
@Component
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private HttpServletRequest request;

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;

    /**
     * 查询用户的id
     * @param
     * @return
     */
    public Long getUserIdByName(){
        String authorization = request.getHeader("authorization");
        Claims claims = JwtUtil.parseJWT(secretKey, authorization);

        Long id = sysUserMapper.selectSysUserByName(claims.get("username").toString());

        return id;
    }


    public LoginUserVo getLoginUser(){
        String authorization = request.getHeader("authorization");
        Claims claims = JwtUtil.parseJWT(secretKey, authorization);
        LoginUserVo username = sysUserMapper.selectLoginUserByName(claims.get("username").toString());
        return username;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected ResponseResult toAjax(int rows) {
        return rows > 0 ? ResponseResult.success() : ResponseResult.error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected ResponseResult toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public ResponseResult success() {
        return ResponseResult.success();
    }

    /**
     * 返回失败消息
     */
    public ResponseResult error() {
        return ResponseResult.error();
    }

    /**
     * 返回成功消息
     */
    public ResponseResult success(String message) {
        return ResponseResult.success(message);
    }

    /**
     * 返回成功消息
     */
    public ResponseResult success(Object message) {
        return ResponseResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public ResponseResult error(String message) {
        return ResponseResult.error(message);
    }

}
